package com.vogue.supplymall.account.shiro.realm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.vogue.configs.springextend.remote.DelegateResource;
import com.vogue.supplymall.account.domain.bean.ConstantBean;
import com.vogue.supplymall.account.domain.model.BaseCode;
import com.vogue.supplymall.account.domain.model.BaseRegistinfo;
import com.vogue.supplymall.account.domain.model.BaseUserInfo;
import com.vogue.supplymall.account.domain.model.User;
import com.vogue.supplymall.account.domain.service.BaseCodeService;
import com.vogue.supplymall.account.domain.service.BaseRegistinfoService;
import com.vogue.supplymall.account.domain.service.BaseUserInfoService;
import com.vogue.supplymall.account.domain.service.RelUserCodeService;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.account.exception.MissLoginOrganShiroException;
import com.vogue.supplymall.common.domain.dto.OrganInfo;
import com.vogue.supplymall.common.domain.dto.ShopInfo;
import com.vogue.supplymall.common.domain.dto.StoreInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.match.domain.model.MatchOrgan;
import com.vogue.supplymall.match.domain.service.MatchOrganService;
import com.vogue.supplymall.order.domain.model.Account;
import com.vogue.supplymall.order.domain.service.AccountService;
import com.vogue.supplymall.shop.domain.model.Shop;
import com.vogue.supplymall.shop.domain.service.ShopService;

public abstract class AccountBaseAuthorizingRealm extends AuthorizingRealm {

	public static final Logger LOGGER_ACCOUNTBASEAUTHORIZINGREALM = LoggerFactory.getLogger(AccountBaseAuthorizingRealm.class);
	
	@Autowired
	private BaseCodeService baseCodeService;

	@Autowired
	private RelUserCodeService relUserCodeService;
	
	@Autowired
	private BaseRegistinfoService baseRegistinfoService;
	
	@Autowired
	private BaseUserInfoService baseUserInfoService;
	
	@DelegateResource
	private MatchOrganService matchOrganService;
	
	@DelegateResource
	private ShopService shopService;
	
	@DelegateResource
	private AccountService accountService;
	
	@Resource
	private UserService userService;
	
	@Autowired
	protected MessageSourceUtils messageSourceUtils;
	
	@SuppressWarnings("rawtypes")
	protected UserInfo loginInfo(User user) throws AuthenticationException{
		
		if(user == null) {
			throw new UnknownAccountException();
		}
		if(user.isDisabledflag()) {
			throw new LockedAccountException();
		}
		UserInfo info = new UserInfo();
		try {
			info.setTel(user.getTel());
			info.setUsername(user.getLoginname());
			info.setLoginId(user.getId());
			info.setSyscodeid(user.getDefsyscodeid());
			info.setName(user.getName());
			info.setHeadImgUrl(user.getHeadimgurl());
			MatchOrgan organ = matchOrganService.selectOneByWhr("type=1 and syscodeid=" + info.getSyscodeid());
			if(organ != null) {
				info.setEntName(organ.getOrgname());
			}		
			
//			if(user.getOrganid() == null || user.getOrganid() == 0L) {
//				info.setLoginUserType(0);
//			}else {
//				info.setLoginUserType(1);
//			}
			//普通企业用户查询关联的管理机构
			String sql = "select o.id organid,o.matchid,o.orgname,o.disabledflag "
					+ "from rel_user_organ ruo, match_organ o "
					+ "where ruo.organid=o.id and o.type in (2,3) and ruo.userid="
					+ user.getId() + " order by o.disabledflag";
			//开通注册的用户查询所有的导入的企业下的机构
			String sqlAdmin = "select id organid,matchid,orgname,disabledflag "
					+ "from match_organ where type in (2,3) and syscodeid="
					+ info.getSyscodeid() + " order by disabledflag";
			List<Map<String, Object>> maplist = null;
			boolean isAdmin = false;//如果是开通手机号则默认是管理员
			//只有供应链系统传过来的新增用户才会isMoflag为true
			if(user.isMoflag()) {			
				maplist = matchOrganService.query(sql);			
			}else {
				BaseRegistinfo registInfo =baseRegistinfoService.selectOneByWhr(//"registtypeid="
						//+ ConstantBean.EnumRegistType.TEL.getCode()
						" syscodeid=" + info.getSyscodeid()
						+ " AND registinfo='" + info.getTel() +"'");
				if(registInfo == null || registInfo.getId() == null || registInfo.getId() == 0L) {
					maplist = matchOrganService.query(sql);	
				}else {
					isAdmin = true;
					maplist = matchOrganService.query(sqlAdmin);					
				}
			}
			
			//是否为个人登录
			boolean isPersonFlag = false;
			//设置当前默认登录机构
			BaseUserInfo bu = baseUserInfoService.selectOneByWhr("userid="+user.getId());
			MatchOrgan o = null;
			if(bu != null) {
				if(bu.getOrganid() != null && bu.getOrganid().longValue() != 0L) {
					o = matchOrganService.get(bu.getOrganid());	
					if (com.vogue.supplymall.common.constant.ConstantBean.PERSON_SHOP_MATCHID.equals(o.getMatchid())) {
						isPersonFlag = true;
					}
				}else {
					isPersonFlag = true;
				}
			} 
			
			if(o == null) {
				if(isAdmin) {
					o = matchOrganService.selectOneByWhr("matchid='" + 
					        com.vogue.supplymall.common.constant.ConstantBean.PERSON_SHOP_MATCHID + 
					        "' and type=2 and syscodeid=" + info.getSyscodeid() );	
					isPersonFlag = true;
				}else {
					if(maplist != null && maplist.size() > 0) {
						Map<String, Object> map = maplist.get(0);
						o = matchOrganService.get(((java.math.BigInteger)map.get("organid")).longValue());
					}
				}
			}
			
			if(o == null) {
				//抛异常缺少必要的管理机构
				//注册的时候为该账号默认添加一个集团以及下属的门店仓库 -- add 2018-09-11	Begin
				MatchOrgan matchOrgan = matchOrganService.selectOneByWhr("type=1 and syscodeid = " + info.getSyscodeid());
				if(matchOrgan == null) {
					matchOrgan = userService.saveDefaultOrgan(messageSourceUtils.getMessage("regist.info.defaultEntName", null), 
							messageSourceUtils.getMessage("regist.info.defaultOrganinfo", null),
							0L,
							info.getSyscodeid(),
							1);
				}
				
				matchOrgan = userService.saveDefaultOrgan(messageSourceUtils.getMessage("regist.info.defaultOrganName", null), 
						messageSourceUtils.getMessage("regist.info.defaultOrganinfo", null),
						matchOrgan.getId(),
						info.getSyscodeid(),
						2);
				
				o = matchOrgan;
				
				matchOrgan = userService.saveDefaultOrgan(messageSourceUtils.getMessage("regist.info.defaultStoreName", null), 
						messageSourceUtils.getMessage("regist.info.defaultOrganinfo", null),
						matchOrgan.getId(),
						info.getSyscodeid(),
						4);
//				throw new MissLoginOrganException();
			}
			
			OrganInfo organInfo= new OrganInfo();
			organInfo.setId(o.getId());
			organInfo.setName(o.getOrgname());
			organInfo.setMatchid(o.getMatchid());
			organInfo.setDisabledflag(o.isDisabledflag());
			info.setOrganInfo(organInfo);						
			//add 2018/08/23 如果登录的身份是个机构员工，那么去查询是否开通的平台账户
			Map<String, Long> params = new HashMap<>();
			params.put("syscodeid", info.getSyscodeid());
			params.put("organid", organInfo.getId());
			Account account = accountService.selectOneByWhr0("syscodeid=#{syscodeid} and organid=#{organid}", params);
			if(account != null) {
				info.setAccountid(account.getId());
			}
			
			List<OrganInfo> organInfoList = new ArrayList<>();
			for(Map<String, Object> map : maplist) {
				organInfo= new OrganInfo();
				organInfo.setId(((java.math.BigInteger)map.get("organid")).longValue());
				organInfo.setName((String)map.get("orgname"));
				organInfo.setMatchid((String)map.get("matchid"));
				organInfo.setDisabledflag((Boolean)map.get("disabledflag"));
				//查有没有店铺
				Shop shop = shopService.selectOneByWhr("organid = " + organInfo.getId());
				if(shop == null || shop.getId() == null || shop.getId() == 0L) {
					organInfo.setShopInfo(null);
				}else {
					ShopInfo shopInfo = new ShopInfo();
					shopInfo.setId(shop.getId());
					shopInfo.setName(shop.getName());
					shopInfo.setMatchid(organInfo.getMatchid());
					shopInfo.setDisabledflag(shop.getDisabledflag());
					shopInfo.setStopflag(shop.getStopflag());
					organInfo.setShopInfo(shopInfo);
				}//查所有下属仓库
				String storesql = isAdmin ? ("select o.id organid,o.matchid,o.orgname "
						+ "from match_organ o "
						+ "where o.type=4 "
						+ "and o.pid=" + organInfo.getId())						 
						: ("select o.id organid,o.matchid,o.orgname "
								+ "from rel_user_organ ruo, match_organ o "
								+ "where ruo.organid=o.id and o.type=4 "
								+ "and o.pid=" + organInfo.getId()
								+ " and ruo.userid = " + user.getId());
				List<Map<String, Object>> storeMapList = matchOrganService.query(storesql);
				List<StoreInfo> storeList = new ArrayList<>();
				for(Map<String, Object> storeMap : storeMapList) {
					StoreInfo storeInfo = new StoreInfo();
					storeInfo.setId(((java.math.BigInteger)storeMap.get("organid")).longValue());
					storeInfo.setName((String)storeMap.get("orgname"));
					storeInfo.setMatchid((String)storeMap.get("matchid"));
					storeList.add(storeInfo);
				}
				organInfo.setStoreList(storeList);
				organInfoList.add(organInfo);
				if(info.getOrganInfo() != null 
						&& info.getOrganInfo().getId().equals(organInfo.getId())) {
					info.setOrganInfo(organInfo);
				}
//				if(user.getOrganid() != null && organInfo.getId() != null
//						&& user.getOrganid().equals(organInfo.getId())) {
//					info.setOrganInfo(organInfo);
//				}
			}
			//绑定用户可切换的机构信息
			info.setOrganList(organInfoList);
			
			if(organInfoList.size() == 0) {
				throw new MissLoginOrganShiroException();
			}
			//设置用户类型
			info.setSelOrgFlag(organInfoList.size() > 1 ? true : false);
			
//			if(organInfoList.size() > 1) {
//				info.setSelOrgFlag(true);
//			}else {
//				List<RelUserCode> rucList = relUserCodeService.selectByWhr("userid=" + user.getId());
//				if(rucList.size() > 0) {				
//					StringBuffer buf = new StringBuffer();
//					for(RelUserCode ruc : rucList) {
//						buf.append(",").append(ruc.getSyscodeid());
//					}	
//					List organList = matchOrganService.selectByWhr("type=2 and syscodeid in ("
//							+ buf.substring(1) 
//							+ ")");
//					if(organList.size() > 1) {
//						info.setSelOrgFlag(true);
//					}else {
//						info.setSelOrgFlag(false);
//					}
//				}else {
//					info.setSelOrgFlag(false);
//				}	
//			}

			if(info.getSyscodeid() != null) {
				BaseCode code = baseCodeService.get(info.getSyscodeid());
				if(code != null) {
					info.setSyscode(code.getSyscode());
				}				
			}		
			
			//判断当前登录人是什么身份，企业员工还是个人
//			BaseUserInfo buinfo = baseUserInfoService.selectOneByWhr("userid=" 
//				+ info.getLoginId()
//				+ " and syscodeid=" 
//				+ info.getSyscodeid());
//			if(buinfo != null && buinfo.getOrganid().longValue() != 0L) {
//				MatchOrgan mo = matchOrganService.get(buinfo.getOrganid());
//				if(mo == null || mo.getId() == null || mo.getId().longValue() == 0L) {
//					info.setLoginUserType(0);//个人
//				}else {
//					if("".equals(mo.getMatchid())) {
//						info.setLoginUserType(0);//个人
//					}else {
//						info.setLoginUserType(1);//企业员工
//					}					
//				}				
//			}else {
//				info.setLoginUserType(0);//个人
//			}
			if(isPersonFlag) {
				info.setLoginUserType(0);//个人
			}else {
				info.setLoginUserType(1);//企业员工
			}
			
			info.setIsAdmin(isAdmin);
		}catch(MissLoginOrganShiroException ex) {
		    LOGGER_ACCOUNTBASEAUTHORIZINGREALM.error("缺少必要的机构......");
			throw ex;
		}catch(Exception ex) {
		    LOGGER_ACCOUNTBASEAUTHORIZINGREALM.error(ex.getMessage());
			throw new AuthenticationException(ex.getMessage());
		}		
		return info;
	}
}
